#include "widget.h"
#include "ui_widget.h"
#include <QHostAddress>
#include <QMessageBox>
#include <QJsonObject>
#include <QJsonDocument>
#include "smarthome.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    socket = new QTcpSocket;
    socket->connectToHost(QHostAddress("110.42.167.18"), 1884);

    connect(socket, &QTcpSocket::connected, [this]()
    {
        QMessageBox::information(this, "连接提示", "连接服务器成功");
    });

    connect(socket, &QTcpSocket::disconnected, [this]()
    {
        QMessageBox::warning(this, "连接提示", "服务器断开连接");
    });

    connect(socket, &QTcpSocket::readyRead, this, &Widget::server_reply_slot);

    this->setWindowTitle("学益得智能硬件");
    ui->pwdEdit->setEchoMode(QLineEdit::Password);
    QFont font("微软雅黑", 14);
    ui->idEdit->setFont(font);
    ui->pwdEdit->setFont(font);

}

Widget::~Widget()
{
    delete ui;
}

void Widget::server_reply_slot()
{
    QByteArray ba = socket->readAll();

    QJsonObject obj = QJsonDocument::fromJson(ba).object();

    if (obj.value("cmd").toString() == "register")
    {
        if(obj.value("result").toString() == "success")
        {
            QMessageBox::information(this, "注册提示", "注册成功");
        }
        else if (obj.value("result").toString() == "exist")
        {
            QMessageBox::warning(this, "注册提示", "注册失败");
        }
    }
    else if (obj.value("cmd").toString() == "login")
    {
        QString result = obj.value("result").toString();

        if (result == "passworderror")
        {
            QMessageBox::warning(this, "登录提示", "登录成功");
        }
        else if (result == "notexist")
        {
            QMessageBox::warning(this, "登录提示", "用户不存在");
        }
        else if (result == "success")
        {
            SmartHome *sh = new SmartHome(deviceid);

            socket->disconnect(SIGNAL(readyRead()));
            socket->disconnect(SIGNAL(disconnected()));

            delete socket;

            sh->show();

            this->close();
        }
    }
}

void Widget::on_regButton_clicked()
{
    QString id = ui->idEdit->text();
    QString pwd = ui->pwdEdit->text();

    QJsonObject obj;
    obj.insert("username", id);
    obj.insert("password", pwd);

    QByteArray ba = QJsonDocument(obj).toJson();
    ba.insert(0, 0x50);

    socket->write(ba);
}

void Widget::on_loginButton_clicked()
{
    deviceid = ui->idEdit->text();
    QString pwd = ui->pwdEdit->text();

    QJsonObject obj;
    obj.insert("username", deviceid);
    obj.insert("password", pwd);

    QByteArray ba = QJsonDocument(obj).toJson();
    ba.insert(0, 0x60);

    socket->write(ba);
}
